package JUC_study;

/**
 *volatile的作用：
 * 保证线程之间的可见性(CPU支持，缓存一致性协议)
 * 禁止指令重排序
 */
public class Volatile_study {
    private static volatile Volatile_study INSTANCE; //JIT

    private Volatile_study() {
    }

    public static Volatile_study getInstance() {
        if (INSTANCE == null) {
            //双重检查
            synchronized (Volatile_study.class) {
                if(INSTANCE == null) {
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    INSTANCE = new Volatile_study();
                }
            }
        }
        return INSTANCE;
    }

    public void m() {
        System.out.println("m");
    }

    public static void main(String[] args) {
        for(int i=0; i<100; i++) {
            new Thread(()->{
                System.out.println(Volatile_study.getInstance().hashCode());
            }).start();
        }
    }

}
